package com.example.wechatdaka.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.wechatdaka.entity.RoleMenu;
import com.example.wechatdaka.entity.RoleMenuSwitch;
import com.example.wechatdaka.service.RoleMenuService;
import com.example.wechatdaka.utils.Result;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lx
 * @since 2020-11-21
 */
@RestController
@RequestMapping("/rolemenu")
public class RoleMenuController {
    @Autowired
    private RoleMenuService roleMenuService;
    @RequestMapping(value = "/findByRoleId",method = RequestMethod.POST)
    public Result findByRoleId( @RequestBody String id){
        QueryWrapper<RoleMenu> roleMenuQueryWrapper=new QueryWrapper<>();
        roleMenuQueryWrapper.eq("lxRoleId",id);
        RoleMenu roleMenu = roleMenuService.getOne(roleMenuQueryWrapper);
        if (roleMenu==null){
            RoleMenuSwitch roleMenuSwitch = new RoleMenuSwitch();
            roleMenuSwitch.setLxRoleId(id);
            return new Result(Result.SUCCESS,roleMenuSwitch,"sucess");
        }
        String [] arr=roleMenu.getLxMenuId().split(",");
        List<Integer> list=new ArrayList<Integer>();
        if (roleMenu.getLxMenuId()!=null&&!"".equals(roleMenu.getLxMenuId())){
            for (int i = 0; i < arr.length; i++) {
                int num=Integer.valueOf(arr[i]);
                list.add(num);
            }
        }
        RoleMenuSwitch roleMenuSwitch = new RoleMenuSwitch();
        roleMenuSwitch.setId(roleMenu.getId());
        roleMenuSwitch.setLxRoleId(roleMenu.getLxRoleId());
        roleMenuSwitch.setLxMenuId(list);

        return new Result(Result.SUCCESS,roleMenuSwitch,"sucess");
    }
    @RequestMapping(value = "/addOrUpdate",method = RequestMethod.POST)
    public Result addOrUpdate( @RequestBody RoleMenuSwitch menuSwitch){
        List<Integer> integerList = menuSwitch.getLxMenuId();
        String str="";
        for (int i = 0; i < integerList.size(); i++) {
            if (i==integerList.size()-1){
                str=str+integerList.get(i);
            }else {
                str=str+integerList.get(i)+",";
            }
        }
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setId(menuSwitch.getId());
        roleMenu.setLxRoleId(menuSwitch.getLxRoleId());
        roleMenu.setLxMenuId(str);
        boolean saveOrUpdate = roleMenuService.saveOrUpdate(roleMenu);
        if (saveOrUpdate){
            return new Result(Result.SUCCESS,null,"sucess");
        }

        return new Result(Result.ERROR,null,"error");
    }




}

